package com.quarkus.resource;

import org.eclipse.microprofile.jwt.JsonWebToken;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

/**
 * @version v1.0
 * @Description: TODO(一句话描述该类的功能)
 * @Author: TongRui乀
 * @Date: 2021/3/7 9:41 上午
 */
@Path("jwt")
@RequestScoped
public class JwtResource {


    @Inject
    JsonWebToken jwt;

    @GET
    @Path("unsecured")
    public String unsecured(@Context SecurityContext context){

        return getResponseString(context);
    }

    @GET
    @Path("permitAll")
    @PermitAll
    public String permitAll(@Context SecurityContext context){
        return getResponseString(context);
    }

    @GET
    @Path("hasRole")
    @RolesAllowed({"User", "Admin1"})
    public String hasRole(@Context SecurityContext context){
        return getResponseString(context);
    }

    /**
     * @Description: 
     * @param @param 从JWT中获取返回值
     * @return @return 
     * @author TongRui乀
     * @throws
     * @date 2021/3/7 9:43 上午
     */
    private String getResponseString(SecurityContext ctx) {
        String name;
        if (ctx.getUserPrincipal() == null) {
            name = "anonymous";
        } else if (!ctx.getUserPrincipal().getName().equals(jwt.getName())) {
            throw new InternalServerErrorException("Principal and JsonWebToken names do not match");
        } else {
            name = ctx.getUserPrincipal().getName();
        }
        return String.format("hello + %s,"
                        + " isHttps: %s,"
                        + " authScheme: %s,"
                        + " hasJWT: %s",
                name, ctx.isSecure(), ctx.getAuthenticationScheme(), hasJwt());
    }

    private boolean hasJwt() {
        return jwt.getClaimNames() != null;
    }
}
